#include "mytcpserver.h"
#include <QDebug>

MyTcpServer::MyTcpServer()
{

}

MyTcpServer &MyTcpServer::getInstance()
{
    static MyTcpServer instance;
    return  instance;

}

void MyTcpServer::incomingConnection(qintptr socketDescriptor)
{
    qDebug()<<"new client connected";
    MyTcpSocket *pTcpSocket = new MyTcpSocket;
    pTcpSocket->setSocketDescriptor(socketDescriptor);
    m_tcpSocetList.append(pTcpSocket);

    connect(pTcpSocket, SIGNAL(offline(MyTcpSocket*)),
            this, SLOT(deleteSocket(MyTcpSocket*)));

}

void MyTcpServer::resend(const char *pername, PDU *pdu)
{
    if(NULL ==pername || NULL ==pdu)
    {
        return;
    }
    QString strName = pername;
    for(int i=0; i<m_tcpSocetList.size(); i++)
    {
       if(strName == m_tcpSocetList.at(i)->getName())
       {
           m_tcpSocetList.at(i)->write((char*)pdu, pdu->uiPDULen);
           break;
       }
    }


}

//删除当前登录用户的socket
void MyTcpServer::deleteSocket(MyTcpSocket *mysocket)
{
    QList<MyTcpSocket*>::iterator iter = m_tcpSocetList.begin();
    for(; iter !=m_tcpSocetList.end(); iter++)
    {
        if(mysocket ==*iter)
        {
            delete *iter;
            *iter = NULL;
            m_tcpSocetList.erase(iter);
            break;
        }
    }
}
